<template>
  <div class="panel-container">
    <t-card class="panel-card-container" :bordered="false">
      <!-- 修改搜索区域的布局 -->
      <t-row :gutter="[16, 16]" justify="space-between">
        <t-col flex="auto">
          <t-row :gutter="[16, 16]">
            <t-col :span="2">
              <t-select
                v-model="searchForm.platformName"
                placeholder="请选择平台"
                :options="platformOptions"
                @change="handlePlatformChange"
              />
            </t-col>
            <t-col :span="2">
              <t-select
                v-model="searchForm.crawlerType"
                placeholder="请选择爬取类型"
                :options="crawlerTypeOptions"
                @change="handleCrawlerTypeChange"
              />
            </t-col>
            <t-col :span="2" v-if="showKeywordSelect">
              <t-select
                v-model="searchForm.keyword" 
                placeholder="请选择关键词" 
                :options="keywordOptions" 
              />
            </t-col>
          </t-row>
        </t-col>
        <t-col flex="none">
          <t-button type="primary" @click="handleSearch">查询</t-button>
        </t-col>
      </t-row>
      <!-- 表格区域 -->
      <t-table
        v-model:displayColumns="displayColumns"
        :data="tableData"
        :columns="columns"
        :column-controller="columnControllerConfig"
        :loading="loading"
        :pagination="pagination"
        :sort="sort"
        multiple-sort
        @sort-change="handleSortChange"
        @page-change="onPageChange"
        stripe
        row-key="task_id"
        style="margin-top: 16px"
      />
    </t-card>
  </div>
</template>

<script>
export default {
  name: 'CommonTable',
  data() {
    return {
      searchForm: {
        platformName: '',
        crawlerType: '',
        keyword: '',
      },
      sort: [],
      platformOptions: [],
      crawlerTypeOptions: [],
      keywordOptions: [],
      showKeywordSelect: false,
      tableData: [],
      loading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      selectedTaskId: null,
      columns: [],
      // 存储所有配置数据
      allConfigs: [],
      // 平台名称映射
      platformMapping: {
        知乎: 'zhihu',
        微博: 'weibo',
        B站: 'bilibili',
        抖音: 'douyin',
        小红书: 'xhs',
      },
      displayColumns: [], // 当前显示的列
      originalData: [], // 用于存储原始数据
    };
  },
  computed: {
    columnControllerConfig() {
      return {
        placement: 'top-right',
        fields: this.columns.map(col => col.colKey),
        displayType: 'auto',
        dialogProps: { preventScrollThrough: true },
        groupColumns: [{
          label: `${this.searchForm.platformName}列`,
          value: 'platform',
          columns: this.columns.map(col => col.colKey)
        }]
      }
    },
  },
  watch: {
    'searchForm.platformName': {
      handler(newVal) {
        if (newVal) {
          this.updateColumns();
          this.filterCrawlerTypes();
          // 初始化显示所有列
          this.displayColumns = this.columns.map(col => col.colKey);
          // 确保操作列显示
          if (!this.displayColumns.includes('operation')) {
            this.displayColumns.push('operation');
          }
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.loadInitialData();
  },
  methods: {
    async loadInitialData() {
      try {
        this.loading = true;
        const response = await this.$request.get('/system/crawler-configs/');
        const { data } = response;
        // 保存所有配置数据
        this.allConfigs = data;

        // 处理平台选项
        const platforms = new Set(data.map((item) => item.platform_name));
        this.platformOptions = Array.from(platforms).map((platform) => ({
          label: platform,
          value: platform,
        }));
      } catch (error) {
        this.$message.error('加载数据失败');
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    // 根据选择的平台筛选爬虫类型
    filterCrawlerTypes() {
      if (!this.searchForm.platformName) {
        this.crawlerTypeOptions = [];
        return;
      }
      const filteredConfigs = this.allConfigs.filter((config) => config.platform_name === this.searchForm.platformName);
      const types = new Set(filteredConfigs.map((item) => item.crawler_type));
      this.crawlerTypeOptions = Array.from(types).map((type) => ({
        label: type,
        value: type,
      }));
    },

    handlePlatformChange() {
      this.searchForm.crawlerType = '';
      this.searchForm.keyword = '';
      this.showKeywordSelect = false;
      this.updateColumns();
      this.filterCrawlerTypes();
    },

    async handleCrawlerTypeChange() {
      if (!this.searchForm.platformName || !this.searchForm.crawlerType) {
        this.showKeywordSelect = false;
        return;
      }

      // 从已有的配置数据中筛选关键词
      const filteredConfigs = this.allConfigs.filter(
        (config) =>
          config.platform_name === this.searchForm.platformName && config.crawler_type === this.searchForm.crawlerType,
      );

      // 如果是关键词搜索类型，显示关键词选择框
      if (this.searchForm.crawlerType === '关键词搜索') {
        const keywords = new Set(filteredConfigs.map((item) => item.keyword).filter(Boolean));
        this.keywordOptions = Array.from(keywords).map((keyword) => ({
          label: keyword,
          value: keyword,
        }));
        this.showKeywordSelect = true;
      } else {
        this.showKeywordSelect = false;
      }
    },

    updateColumns() {
      // 根据不同平台设置不同的列
      const commonColumns = [
        { 
          colKey: 'created_time', 
          title: '创建时间', 
          width: 180,
          sorter: true,
          sortType: 'all'
        }
      ];

      const platformColumns = {
        zhihu: [
          { colKey: 'title', title: '标题', width: 200 },
          { colKey: 'voteup_count', title: '点赞数', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'comment_count', title: '评论数', width: 100, sorter: true, sortType: 'all' },
        ],
        weibo: [
          { colKey: 'user_name', title: '用户名', width: 120 },
          { colKey: 'content', title: '微博内容', width: 300 },
          { colKey: 'repost_count', title: '转发数', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'comment_count', title: '评论数', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'like_count', title: '点赞数', width: 100, sorter: true, sortType: 'all' },
        ],
        bilibili: [
          { colKey: 'title', title: '视频标题', width: 200 },
          { colKey: 'author', title: 'UP主', width: 120 },
          { colKey: 'view_count', title: '播放量', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'danmaku_count', title: '弹幕数', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'like_count', title: '点赞数', width: 100, sorter: true, sortType: 'all' },
        ],
        douyin: [
          { colKey: 'author_name', title: '作者', width: 120 },
          { colKey: 'content', title: '视频描述', width: 300 },
          { colKey: 'like_count', title: '点赞数', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'comment_count', title: '评论数', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'share_count', title: '分享数', width: 100, sorter: true, sortType: 'all' },
        ],
        xhs: [
          { colKey: 'title', title: '标题', width: 200 },
          { colKey: 'add_ts', title: '添加时间', width: 120, sorter: true, sortType: 'all' },
          { colKey: 'time', title: '发布时间', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'last_update_time', title: '最后更新时间', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'like_count', title: '点赞数', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'comment_count', title: '评论数', width: 100, sorter: true, sortType: 'all' },
          { colKey: 'collect_count', title: '收藏数', width: 100, sorter: true, sortType: 'all' },
        ],
      };

      const platformCode = this.platformMapping[this.searchForm.platformName];
      this.columns = [...commonColumns, ...(platformColumns[platformCode] || [])];
    },

    // 处理排序变化
    handleSortChange(val) {
      this.sort = val;
      // 根据排序重新获取数据
      this.handleSearch();
    },

    async handleSearch() {
      try {
        this.loading = true;
        const matchedConfig = this.allConfigs.find(
          (config) =>
            config.platform_name === this.searchForm.platformName &&
            config.crawler_type === this.searchForm.crawlerType &&
            (this.searchForm.crawlerType !== '关键词搜索' || config.keyword === this.searchForm.keyword),
        );

        if (matchedConfig) {
          // 获取平台数据时添加排序参数
          const dataResponse = await this.$request.get(`/system/platform-data/${matchedConfig.task_id}/`, {
            params: {
              platform_name: this.platformMapping[this.searchForm.platformName],
              sort: this.sort, // 添加排序参数
            },
          });

          if (dataResponse.code === 0) {
            this.tableData = dataResponse.data;
            this.pagination.total = dataResponse.data.length;
            this.pagination.current = 1;
          } else {
            this.$message.error(dataResponse.message || '获取数据失败');
          }
        } else {
          this.$message.warning('未找到匹配的配置信息');
          this.tableData = [];
          this.pagination.total = 0;
        }
      } catch (error) {
        this.$message.error('搜索失败');
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    onPageChange(current) {
      this.pagination.current = current;
    },

    handleDisplayColumnsChange() {
      // 可以在这里处理列显示变化后的逻辑
      console.log('显示列发生变化:', this.displayColumns);
    }
  },
};
</script>

<style lang="less" scoped>
.panel-container {
  .panel-card-container {
    padding: 16px;
  }
}
</style>
